package com.aaa.gs.service.impl;

import com.aaa.common.entity.*;
import com.aaa.common.util.Result;
import com.aaa.common.util.TokenUtil;
import com.aaa.common.vo.GoodsImageVO;
import com.aaa.common.vo.ProductVO;
import com.aaa.gs.dao.ProductDao;
import com.aaa.gs.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.aaa.common.util.CustomException;
import com.aaa.common.util.ResultStatus;
import com.aaa.common.vo.Page;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * (Product)表服务实现类
 *
 * @author makejava
 * @since 2025-09-16 09:15:02
 */
@Service("productService")
public class ProductServiceImpl implements ProductService {
    private static final Logger log = LoggerFactory.getLogger(ProductServiceImpl.class);
    @Resource
    private ProductDao productDao;
    @Resource
    private ProductExamineService productExamineService;
    @Resource
    private GoodsImageService goodsImageService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private RemoteRoleService remoteRoleService;
    @Resource
    private RemoteStoreService remoteStoreService;

    /**
     * 修改月销量
     * @param productId
     * @return
     */
    @Override
    public int updateMonthlySales(Integer productId) {
        return productDao.updateMonthlySales(productId);
    }

    /**
     * 查询所有数据
     *
     * @return 对象列表
     */
    @Override
    public List<ProductVO> queryAll(ProductVO  product) {
        //product.setStoreId(product.getStore().getStoreId());
        //return productDao.queryAll(product);
        return productDao.queryAllByLimit( product);
    }

    /**
     * 通过ID查询单条数据
     * @param productId 主键
     * @return 实例对象
     */
    @Override
    public ProductVO queryById(Integer productId) {
        return this.productDao.queryById(productId);
    }

    /**
     * 分页查询
     * @param page 筛选条件
     * @return 查询结果
     */
    @Override
    public PageInfo queryByPage(Page<ProductVO> page) {
        //分页操作  分页参数一定要进行传递
        if (page == null || page.getPageNo() == null || page.getPageNo() == 0 || page.getPageSize() == null || page.getPageSize() == 0) {
            page.setPageNo(1);
            page.setPageSize(10000);
           /* //进行业务编写时，可以抛出自定义异常
            throw new CustomException(ResultStatus.PARAM_NOT_EMPTY.getReturnCode(),
                    ResultStatus.PARAM_NOT_EMPTY.getReturnMessage());*/
        }
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        //获取查询对象
        ProductVO product = page.getData();
        //获取当前用户
        Integer userId = Integer.valueOf(TokenUtil.getUserId(request));
        //获取当前用户的角色
        List<String> roleKeyList = remoteRoleService.queryRoleKey(userId); // 远程调用获取角色列表
        log.info("当前用户ID：{}，角色列表：{}", userId, roleKeyList);
        if (roleKeyList.contains("guanliyuan")) {
            //管理员
            log.info("当前用户是管理员");
        } else if (roleKeyList.contains("laoban")) {
            //店铺
            log.info("当前用户是老板");
            //获取当前用户的店铺
            Store storeQuery  = new Store();
            storeQuery .setUserId(userId);
            List<Store> storeList = remoteStoreService.selectMyStore(storeQuery );
            // 收集店铺ID列表，用于过滤商品
            List<Integer> storeIds = new ArrayList<>();
            for (Store store : storeList) {
                storeIds.add(store.getStoreId());
            }
           product.setStoreIds(storeIds);
        }

        //查询商品列表，关联创建人信息
        List<ProductVO> productList  = productDao.queryAllByLimit(product);
        //循环遍历商品列表
        for (ProductVO p : productList) {
            //处理创建人信息
            if (p.getCreateId() != null){
                User createUser = remoteUserService.queryById(p.getCreateId());
                log.info("==============创建人信息："+createUser);
                p.setUserA( createUser);
            }else{
                p.setUserA(new User());
            }
            //处理更新人信息
            if (p.getUpdateId() != null){
                User updateUser = remoteUserService.queryById(p.getUpdateId());
                log.info("==============更新人信息："+updateUser);
                p.setUserB( updateUser);
            }else{
                p.setUserB(new User());
            }
        }
        //return new PageInfo(productDao.queryAllByLimit(product));
        return new PageInfo(productList);
    }

    /**
     * 新增数据
     * @param product 实例对象
     * @return 实例对象
     */
    @Override
    public Product insert(Product product) {
        String userId = TokenUtil.getUserId(request);
        product.setCreateId(Integer.parseInt(userId));
        product.setCreateTime(new Date());
        this.productDao.insert(product);

        //修改审核表
        ProductExamine examine = new ProductExamine();
        examine.setStoreId(product.getStoreId());
        examine.setProductId(product.getProductId());
        examine.setProTypeId(product.getProTypeId());
        examine.setName(product.getProductName());
        examine.setPicture(product.getPicture());
        examine.setLoadPrice(product.getLoadPrice());
        examine.setNewPrice(product.getNewPrice());
        examine.setPointsenabled(product.getIntegralEnabled());
        examine.setPoints(product.getIntegral());
        examine.setMonthlySales(product.getMonthlySales());
        examine.setIsFreightShipping(product.getIsFreightShipping());
        examine.setFreight(product.getFreight());
        examine.setIsline(product.getIsline());
        examine.setProductDetails(product.getProductDetails());
        examine.setPrompt(product.getPrompt());
        examine.setIsExamine(product.getExamineStatus());
        productExamineService.insert(examine);

        //创建goodsImage表
        GoodsImage goodsImage = new GoodsImage();
        goodsImage.setProductId(product.getProductId());
        goodsImage.setImageName(product.getProductName());
        goodsImage.setImageurl(product.getPicture());
        goodsImage.setCreator(product.getCreateId());
        goodsImageService.insert(goodsImage);

        return product;
    }

    /**
     * 修改数据(更新人，商品图片)
     * @param product 实例对象
     * @return 实例对象
     */
    @Override
    public ProductVO update(ProductVO product) {
        String userId = TokenUtil.getUserId(request);
        product.setUpdateId(Integer.parseInt(userId));
        product.setUpdateTime(new Date());
        this.productDao.update(product);
        //修改审核表
        /*ProductExamine examine = new ProductExamine();
        examine.setStoreId(product.getStoreId());
        examine.setProductId(product.getProductId());
        examine.setProTypeId(product.getProTypeId());
        examine.setName(product.getProductName());
        examine.setPicture(product.getPicture());
        examine.setLoadPrice(product.getLoadPrice());
        examine.setNewPrice(product.getNewPrice());
        examine.setPointsenabled(product.getIntegralEnabled());
        examine.setPoints(product.getIntegral());
        examine.setMonthlySales(product.getMonthlySales());
        examine.setIsFreightShipping(product.getIsFreightShipping());
        examine.setFreight(product.getFreight());
        examine.setIsline(product.getIsline());
        examine.setProductDetails(product.getProductDetails());
        examine.setPrompt(product.getPrompt());
        examine.setIsExamine(product.getExamineStatus());
        productExamineService.insert(examine);*/

        //修改goodsImage表
        GoodsImageVO goodsImage = new GoodsImageVO();
        goodsImage.setProductId(product.getProductId());
        goodsImage.setImageName(product.getProductName());
        goodsImage.setImageurl(product.getPicture());
        goodsImageService.update(goodsImage);
        return this.queryById(product.getProductId());
    }

    /**
     * 通过主键删除数据
     *
     * @param productId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer productId) {
        return this.productDao.deleteById(productId) > 0;
    }
}
